package com.hxlc.util;

import cn.hutool.core.io.resource.ResourceUtil;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;

/**
 * @author t-zhaoheng
 * @since 2022/2/21
 */
@Component
public class FileReadUtil {
    public static void main(String[] args) {
        URL url = ResourceUtil.getResource("static/json/station/national.json");
        String urlFile = url.getFile();
        String urlPath = url.getPath();
        System.out.println("urlFile:" + urlFile);
        System.out.println("urlPath:" + urlPath);
    }

    private static final FileReadUtil INSTANCE = new FileReadUtil();

    private FileReadUtil() {
    }

    public static FileReadUtil getInstance() {
        return INSTANCE;
    }

    /**
     * @param filePath 文件路径
     * @return InputStream of this file
     */
    private InputStream getInputStream(String filePath) {
        return this.getClass().getClassLoader().getResourceAsStream(filePath);
    }

    /**
     * 将 InputStream 读取称为 String
     *
     * @param inputStream 输出流
     * @return String of the inputStream
     */
    private String getString(InputStream inputStream) {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuffer = new StringBuilder();
        String line = null;
        try {
            line = bufferedReader.readLine();
            while (line != null) {
                stringBuffer.append(line);
                line = bufferedReader.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuffer.toString();
    }

    /**
     * 读取jar包中自带的资源文件
     */
    public String getString(String filePath) {
        return getString(getInputStream(filePath));
    }

    /**
     * 读取服务器本地的文件
     */
    public String getLocalFile(String filePath) {
        String result = "";
        File file = new File(filePath);
        if (!file.exists()) {
            return null;
        } else {
            try {
                InputStream fileInputStream = new FileInputStream(file);
                result = getString(fileInputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

}